<script setup>
import { reactive, ref, toRefs, computed, onMounted } from 'vue';
import {
  queryPagePcbaSmtBomOrderExpressList,
  queryPagePcbaSmtPcbExpressMaterialsList,
  queryPagePcbaWaitExpressMaterialsList,
  createPcbaOrderExpress,
} from '@/server/api/biz.js';
import Table from '@/components/Table/index.vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import Pagination from '@/components/Pagination/index.vue';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: undefined,
  },
});
const { queryParams } = toRefs(data);

const formRef = ref();
const router = useRouter();
const form = reactive({
  contacts: '',
  telephone: '',
  expressName: '',
  expressList: [
    {
      expressNo: '',
      id: Date.now(),
    },
  ],
});

const mailingData = reactive({
  MailId: [],
  bomData: [],
  pcbData: [],
  list: {
    pageNumber: 1,
    pageSize: 10,
    totalRow: 0,
  },
  pcbList: {
    pageNumber: 1,
    pageSize: 10,
    totalRow: 0,
  },
  expressNoList: '',
  isCheck: false,
});

const rules = reactive({
  contacts: [{ required: true, message: t('om.Pleaseenteranemailcontact'), trigger: 'blur' }],
  telephone: [{ required: true, message: t('om.contactphonenumber'), trigger: 'blur' }],
  expressNo: [{ required: true, message: t('om.Pleaseenterthecouriernumber'), trigger: 'blur' }],
  expressName: [{ required: true, message: t('om.nameofthecourier'), trigger: 'blur' }],
});

// 邮寄元器件表格表头
const bomColumns = computed(() => [
  {
    label: t('om.MailingComponents'),
    prop: 'model',
  },
  {
    label: t('om.MailingQuantity'),
    prop: 'confirmMailing',
  },
]);

// pcb邮寄元器件表格表头
const pcbColumns = computed(() => [
  {
    label: t('om.MailedPCBs'),
    prop: 'elementInfo',
  },
  {
    label: t('om.MailingQuantity'),
    prop: 'totalQuantity',
  },
]);

// 添加快递单号行
const addRow = () => {
  form.expressList.push({
    expressNo: '',
    id: Date.now(),
  });
  console.log(form.expressList);
};

// 删除快递单号行
const deleteRow = (item, index) => {
  console.log(item, index);
  form.expressList.splice(index, 1);
};

// 确认邮寄
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      getExpressNoList();
      if (mailingData.isCheck == true) {
        submitExpress();
      } else {
        ElMessage.error('请阅读并同意《物料邮寄注意事项》');
      }
    } else {
      ElMessage.error('请填写必填项');
    }
  });
};

const getExpressNoList = () => {
  const arr = [];
  form.expressList.forEach((item) => {
    arr.push(item.expressNo);
  });
  mailingData.expressNoList = arr.join(',');
};

/**
 * 获取所有邮寄元器件列表
 */
const getAllListId = () => {
  const obj = {
    bomId: 0,
    customerAccountId: 0,
    expressId: 0,
    limit: 10,
    materialsType: 0,
    orderStatus: 0,
    page: 1,
    pageType: 0,
    pcbOrderId: 0,
    pcbaOrderId: 0,
    productId: 0,
    serial: '',
    smtOrderDetailId: 0,
    smtOrderId: 0,
  };
  queryPagePcbaWaitExpressMaterialsList(obj).then((res) => {
    if (res.code === 200) {
      console.log(res, 333);
      getMailId(res.data);
    } else {
      ElMessage.error(res.msg);
    }
  });
};

/**
 * 重组ID
 * @param {*} data
 */
const getMailId = (data) => {
  const arr = [];
  data.forEach((item) => {
    arr.push(item.id);
  });
  console.log(arr);
  mailingData.MailId = arr;
};

/**
 * 获取bom邮寄列表
 */
const getBomlist = (page = 1, limit = 10) => {
  mailingData.bomData = [];
  const obj = {
    bomId: 0,
    customerAccountId: 0,
    expressId: 0,
    limit: limit,
    materialsType: 0,
    orderStatus: 0,
    page: page,
    pageType: 1,
    pcbOrderId: 0,
    pcbaOrderId: 0,
    productId: 0,
    serial: '',
    smtOrderDetailId: 0,
    smtOrderId: 0,
  };
  queryPagePcbaSmtBomOrderExpressList(obj).then((res) => {
    if (res.code === 200) {
      mailingData.bomData = res.data.list;
      mailingData.list = res.data;
      console.log(res, 111);
    } else {
      ElMessage.error(res.msg);
    }
  });
};

/**
 * 获取pcb邮寄列表
 */
const getPcblist = (page = 1, limit = 10) => {
  mailingData.pcbData = [];
  const obj = {
    bomId: 0,
    customerAccountId: 0,
    expressId: 0,
    limit: limit,
    materialsType: 0,
    orderStatus: 0,
    page: page,
    pageType: 1,
    pcbOrderId: 0,
    pcbaOrderId: 0,
    productId: 0,
    serial: '',
    smtOrderDetailId: 0,
    smtOrderId: 0,
  };
  queryPagePcbaSmtPcbExpressMaterialsList(obj).then((res) => {
    if (res.code === 200) {
      mailingData.pcbData = res.data.list;
      mailingData.pcbList = res.data;
      console.log(res, 222);
    } else {
      ElMessage.error(res.msg);
    }
  });
};

/**
 * 确认邮寄
 */
const submitExpress = () => {
  const obj = {
    expressMaterialsIds: mailingData.MailId,
    expressName: form.expressName,
    expressNo: mailingData.expressNoList,
    expressPhone: form.telephone,
    expressUser: form.contacts,
  };
  console.log(obj);
  // return;
  createPcbaOrderExpress(obj).then((res) => {
    if (res.code === 200) {
      router.push({ path: '/order', query: { type: 1, tabs: 1, recordType: 3 } });
    } else {
      ElMessage.error(res.msg);
    }
  });
};

/**
 * 分页
 * @param {*} page
 * @param {*} limit
 */
const handlePaginationChange = (page = 1, limit = 10) => {
  console.log(val);
  getBomlist(page, limit);
};

const handlePaginationPcbChange = (page = 1, limit = 10) => {
  console.log(val);
  getPcblist(page, limit);
};

const goBack = () => {
  router.go(-1);
};

onMounted(() => {
  getAllListId();
  getBomlist();
  getPcblist();
});
</script>
<template>
  <div class="wrapper">
    <div class="confirm-mail container">
      <!-- 收件人信息 -->
      <div class="block-container">
        <h2 class="title">{{ $t('om.ComponentMailingList') }}</h2>
        <p class="row-item">{{ $t('om.addree') }}</p>
        <p class="row-item">{{ $t('om.tel') }}</p>
        <p class="row-item">
          {{ $t('om.AddresseeAddress') }}
        </p>
        <p class="row-item warning">{{ $t('om.Pleasefillintheaddress') }}</p>
      </div>
      <!-- 邮寄信息 -->
      <div class="block-container">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="130px">
          <el-form-item prop="expressName" :label="$t('om.ExpressName')">
            <el-input
              v-model="form.expressName"
              :placeholder="$t('om.nameofthecourier')"
              clearable
              style="width: 260px"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            class="express-form-item"
            :label="`${index == 0 ? $t('om.TrackingNumber') : ''}`"
            v-for="(express, index) in form.expressList"
            :key="index"
            :rules="rules.expressNo"
            :prop="'expressList.' + index + '.expressNo'"
          >
            <el-input
              class="express-input"
              v-model="express.expressNo"
              :placeholder="$t('om.deliverynotenumber')"
              clearable
              style="width: 260px"
            >
            </el-input>
            <el-link type="primary" @click="addRow" v-if="index == 0" style="padding-left: 12px">
              {{ $t('om.AddCourierNumber') }}</el-link
            >
            <el-link
              type="danger"
              v-else
              style="padding-left: 12px"
              @click="deleteRow(express, index)"
            >
              {{ $t('smt.Deleting') }}</el-link
            >
          </el-form-item>
          <el-form-item prop="contacts" :label="$t('om.MailContacts')">
            <el-input
              v-model="form.contacts"
              :placeholder="$t('om.Pleaseenteranemailcontact')"
              clearable
              style="width: 260px"
            >
            </el-input>
          </el-form-item>
          <el-form-item prop="telephone" :label="$t('om.MailContactPhone')">
            <el-input
              v-model="form.telephone"
              :placeholder="$t('om.contactphonenumber')"
              clearable
              style="width: 260px"
            >
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格 -->
      <div class="block-container border-none">
        <h2 class="title">{{ $t('om.ComponentMailingList') }}</h2>
        <!-- 邮寄元器件表格-->
        <Table
          class="component-table"
          serial
          :serialOptions="{ pageNum: queryParams.pageNum, pageSize: queryParams.pageSize }"
          :data="mailingData.bomData"
          :columns="bomColumns"
        >
        </Table>
        <Pagination
          class="m-b-10"
          v-show="mailingData.list.totalRow > 0"
          :total="mailingData.list.totalRow"
          v-model:page="mailingData.list.pageNumber"
          v-model:limit="mailingData.list.pageSize"
          @pagination="handlePaginationChange"
        />
        <!-- 邮寄PCB表格-->
        <Table
          class="pcb-table"
          serial
          :serialOptions="{ pageNum: queryParams.pageNum, pageSize: queryParams.pageSize }"
          :data="mailingData.pcbData"
          :columns="pcbColumns"
        ></Table>
        <Pagination
          class="m-b-10"
          v-show="mailingData.pcbList.totalRow > 0"
          :total="mailingData.pcbList.totalRow"
          v-model:page="mailingData.pcbList.pageNumber"
          v-model:limit="mailingData.pcbList.pageSize"
          @pagination="handlePaginationPcbChange"
        />
      </div>
      <div class="block-container border-none">
        <h2 class="title">{{ $t('om.MailingMaterials') }}</h2>
        <div class="tip-list">
          <p class="tip-item">1. {{ $t('om.Mailingmaterialdoes') }}</p>
          <p class="tip-item">2. {{ $t('om.Inordertospeedup') }}</p>
          <p class="tip-item">3. {{ $t('om.outofthewarehouse') }}</p>
          <p class="tip-item">
            4.
            {{ $t('om.Ifthereisanydiscrepancybetween') }}
          </p>
          <p class="tip-item">5.{{ $t('om.MailingDevices') }}</p>
          <p class="tip-item">6. {{ $t('om.PCBgenerationstarts') }}</p>
          <p class="tip-item">7. {{ $t('om.Thedeliverytime') }}</p>
          <p class="tip-item">8. {{ $t('om.Nopickup') }}</p>
          <p class="tip-item">9. {{ $t('om.acceptbatteriesbymail') }}</p>
        </div>
        <el-checkbox v-model="mailingData.isCheck" label="1" size="large">
          <el-link type="primary">{{ $t('om.Ihavereadandagree') }}</el-link></el-checkbox
        >
        <div class="btn-wrap">
          <el-button type="primary" @click="goBack()">{{ $t('om.CancelMailing') }}</el-button>
          <el-button type="primary" @click="submitForm(formRef)">{{
            $t('om.Confirmationofmailing')
          }}</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.wrapper {
  background: #f5f5f5;
  padding: 32px 0 32px;
  .confirm-mail {
    border-radius: 8px;
    background: #fff;
    &.container {
      width: 1440px;
      margin: 0 auto;
      margin-top: 80px;
    }

    .block-container {
      padding: 24px;
      border-bottom: 1px solid #e5e5e5;
      &.border-none {
        border: none;
      }
      .title {
        padding-bottom: 24px;
        color: #383838;
        font-size: 18px;
        font-weight: 700;
      }

      .row-item {
        padding-bottom: 8px;
        color: #383838;
        font-size: 14px;
        &.warning {
          color: var(--mall-warning-color);
        }
      }

      .tip-list {
        .tip-item {
          padding-bottom: 12px;
          color: #383838;
          font-size: 14px;
        }
      }

      .btn-wrap {
        padding-top: 24px;
        display: flex;
        justify-content: center;
      }
    }

    .pcb-table {
      margin-top: 12px;
    }
  }
}
</style>
